import React from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import constants from 'share/constants'
import {messages, getApprovelHistory, getQueryUrlParam, queryCurrencyPrecision} from 'share/common'
import {Form, Tabs, Affix, Spin, Row, Col, message, Alert, Modal, Button, Tag, Icon, Popover} from 'antd'
import ResizeTable from "components/resize-table";
const TabPane = Tabs.TabPane;
import errorMessage from 'share/errorMessage'

import JDOrderInfo from 'containers/request/jd-request/jd-order-info'
import JDErrorAlert from 'containers/request/jd-request/jd-error-alert'
import BookerInfoAlert from 'containers/request/booker-request/booker-info-alert'
import BookerTicketInfo from 'containers/request/booker-request/ticket-info'
import RescheduleRefundInfo from 'containers/request/booker-request/reschedule-refund-info'
import LoanRelatedApplication from 'containers/request/loan-request/loan-related-application'
import RelatedShowList from 'containers/request/related-show-list'
import TravelInformation from 'containers/request/travel-request/travel-information'
import TravelInformationElement from 'containers/request/travel-request/travel-element-information'
import TravelDate from 'containers/request/travel-request/travel-date'
import TravelPreviousVersion from 'containers/request/travel-request/travel-previous-version'
import TravelOrderList from 'containers/request/travel-request/travel-order-list'

import RecallBtn from 'containers/request/btns/recall-btn'
import GoBackBtn from 'containers/request/btns/go-back-btn'
import TransferBtn from 'containers/request/btns/transfer-btn'
import GoErBtn from 'containers/request/btns/go-er-btn'
import CloseBtn from 'containers/request/btns/close-btn'
import PrintBtn from 'containers/request/btns/print-btn'
import TravelUpdateBtn from 'containers/request/btns/travel-update-btn'
import ExpireBtn from 'containers/request/btns/expire-btn'
import RestartBtn from 'containers/request/btns/restart-btn'
import BookerRefundBtn from 'containers/request/btns/booker-refund-btn'
import BookerEndorseBtn from 'containers/request/btns/booker-endorse-btn'
import ApproveRequestBtn from 'containers/approve/request/approve-request-btn'
import RescheduleRefundBtn from 'containers/approve/reschedule-refund/reschedule-refund-btns'
import PriceReviewBtn from 'containers/approve/price-review/price-review-btn'
import AuditApplicationDetail from 'containers/financial-management/finance-audit/audit-application-detail'
import LoanAndRefundBack from 'containers/financial-management/loan-and-refund/loan-and-refund-back'
import SurePayBtn from 'containers/financial-management/confirm-payment/sure-pay-btn'
import AppointmentBtn from 'containers/request/btns/appointment-btn'
import ConfirmationBtn from 'containers/request/btns/confirmation-btn'
import GiftRequestDetailA from 'containers/request/gift-request-detail/gift-request-detail-a'
import GiftRequestDetailB from 'containers/request/gift-request-detail/gift-request-detail-b'
import GiftRequestDetailC from 'containers/request/gift-request-detail/gift-request-detail-c'
import ReceiverInformation from 'containers/request/gift-request-detail/receiver-information'
import GiftRequestA from 'containers/request/gift-request/gift-request-detail-a'
import GiftRequestB from 'containers/request/gift-request/gift-request-detail-b'
import GiftRequestC from 'containers/request/gift-request/gift-request-detail-c'
import GiftRequestD from 'containers/request/gift-request/gift-request-detail-d'
import GiftReceiverInformation from 'containers/request/gift-request/receiver-information'


import ApproveHistory from 'components/template/approve-history'
import ApproveTag from 'components/template/approve-tag'
import customField from 'share/customField'
import requestService from 'containers/request/request.service'
import baseService from 'share/base.service'
import approveRequestService from 'containers/approve/request/request.service'
import HonestView from 'components/template/honest-view'
import 'styles/request/base-request-detail.scss'
import ExpenseTypeClose from 'containers/request/new-request/expense-type-close'
import ApprovingEdit from 'containers/approve/approving-edit'
import BudgetExplain from 'components/template/budget-explain/budget-explain'
import QrCode from "qrcode.react";
import trafficLineImg from 'images/request/travel/traffic_line.png'
import lowCarbonTravel from "images/request/travel/low-carbon-travel.jpg"
import menuRoute from "routes/menuRoute";
import adminApproveListService from "../setting/process-monitoring-platform/admin-approve-list.service";
import giftDeclareService from './gift-declare/gift-declare-service'
import GiftDeclareDetail from './gift-declare/gift-declare-detail'
import { setGiftDeclareValue } from "./gift-declare/gift-declare-utils";
import UnifiedTable from "components/template/widget/unified-table/UnifiedTable";
import GreenCode from "containers/request/greencode/green-code";
import config from 'config'
import httpFetch from 'share/httpFetch'
import approveService from 'containers/approve/approve.service'

class BaseRequestDetail extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tapValue: 'requestInfo',
      subTabValue: 'detail',
      formOID: '',
      formType: '',
      formInfo: {},
      showNewRepaymentSlide: false,
      info: {}, //申请单详情
      thirdPartyInfo: {}, //第三方返回信息
      approvalChain: {},  //审批链
      approvalHistory: [], //审批历史
      approve: false, //审批页面
      showApproveBottom: false, //是否显示底部审批／驳回等按钮
      audit: false,  //审核页面
      view: false,  //查看页面
      loanRefund: false,  //借还款页面
      rescheduleRefund: false, //退改签页面
      price: false, //价格审核页面
      confirmPay: false, //确认付款页面
      readOnly: false,   //只可读
      payProcess:location.search.indexOf('pay_in_process')>-1,
      /**
       * @type {boolean}
       */
      manageType: null,
      giftDeclareValue: null,
      apportionmentOIDs: [], //可关闭申请单详情页中选择的需要关闭的分摊行oid
      budgetOIDs: [], //可关闭申请单详情页中选择的需要关闭的预算行oid
      buttonRoleSwitch:this.checkPageRole('EXPENSEAUDIT', 2) && this.checkFunctionProfiles(['er.disabled'], [[false, undefined]]) && this.checkFunctionProfiles(['finance.audit.disabled'], [[false, undefined]]), //按钮操作权限
      creditInfo:{},//信用相关数据
      honestModalShow:false,
      isHasBudgetDetail: false, //是否有预算明细控件
      budgetExplainNumber: 0, //预算执行情况列表数量
      mcdGoingArr: [], //线下机票订单数组
      mcdHotelArr: [], //线下酒店订单数组
      flightOrderList: [], //机票确认单所有订单数组
      hotelOrderList: [], //酒店确认单所有订单数组
      mcdFieldValue: {}, //机酒确认单的自定义字段值
      flightOriginjourneyList: [], //机票确认单原甄选订单行程（存在往返）
      hotelOriginjourneyList: {}, // 酒店确认单原甄选订单行程
      fligtFrom: '', //线下机票出发城市
      fligtTo: '', //线下机票到达城市
      cityName: '', //线下酒店城市
      hotelFromDate: '', //线下酒店开始日期
      hotelToDate: '', //线下酒店结束日期
      requestDetail: menuRoute.getRouteItem('request-detail','key'), //申请单详情页
      disablePress: false,
      /**
       * 公共列表
       * @type {{fieldName:string; formField: string; value: string}[]}
       */
      unifiedTableList: [],
      giftA: [],
      giftB: [],
      giftC: [],
      receiver: [],
      submitLoading: false,
      SQ001readOnly: [],
      loseLoading: false,
      signLoading: false,
      confLoading: false
    }
  }

  componentDidMount() {
    this.setState({
      formOID: this.props.params.formOID,
      approve: this.props.location.pathname.indexOf('approve-request-detail') > -1,
      audit: this.props.location.pathname.indexOf('loan-request-detail-audit') > -1,
      view: this.props.location.pathname.indexOf('finance-view') > -1,
      loanRefund: this.props.location.pathname.indexOf('loan-refund-detail') > -1,
      rescheduleRefund: this.props.location.pathname.indexOf('reschedule-refund-detail') > -1,
      price: this.props.location.pathname.indexOf('price-review-detail') > -1,
      confirmPay: this.props.location.pathname.indexOf('confirm-payment') > -1,
      adminApprove: this.props.location.pathname.indexOf('admin-approve-request-detail') > -1,
      costApplication: this.props.location.pathname.indexOf('cost-application-detail') > -1,
    },() => {
      const { approve, audit, view, loanRefund, rescheduleRefund, price, confirmPay, adminApprove } = this.state;
      this.setState({
        readOnly:adminApprove || approve || audit || view || loanRefund || rescheduleRefund || price || confirmPay || this.props.location.query.readOnly,
      });
      this.getFormType(this.state.formOID)
    })
  }

  getFormType = (formOID) => {
    this.setState({ loading: true });
    requestService.getFormType(formOID).then(res => {
      this.setState({
        formType: res.data.formType,
        formInfo: res.data,
        manageType:res.data.customFormProperties.manageType
      },() => {
        this.getInfo(this.state.formType)
      });
    }).catch(e => {
      this.setState({loading: false});
      let error = e.response.data;
      if (error.validationErrors && error.validationErrors.length) {
        message.error(error.validationErrors[0].message)
      } else {
        message.error(error.message)
      }
    })
  };

  getInfo = () => {
    //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
    const { applicationOID, bookTaskOID, pageFrom } = this.props.params;
    let getType = this.state.rescheduleRefund ? 'getBookerTaskRequestDetail' : 'getRequestDetail';
    if (pageFrom === 'closeList') {
      getType = 'getRequestCloseDetail';
    }

    this.setState({ loading: true });
    requestService[getType](applicationOID, bookTaskOID).then(res => {
      this.setState({
        loading: false,
        info: this.state.rescheduleRefund ? res.data.applicationDTO : res.data,
        approvalHistory: this.state.rescheduleRefund ? res.data.approvalHistoryDTOs : res.data.approvalHistorys
      },() => {
        this.updateUnifiedTableList();
        this.getGiftDeclareDetail();
        this.getMcdGoingArr(); //处理线下机票单据的行程数据，用来做特殊行程展示
        this.getMcdHotelArr(); //处理线下酒店单据的行程数据，用来做特殊行程展示
        if (this.state.info.formCode === 'OFFLINE_FLIGHT_CONFIRMATION_FORM' || this.state.info.formCode === 'OFFLINE_HOTEL_CONFIRMATION_FORM') {
          this.handleOrderList();//处理机酒确认单的所有订单，获取原甄选订单内的行程
        }
        this.isShowAmount(); //处理是否有预算明细控件，如果没有该控件，则不展示总金额
        this.getThirdPartyInfo();
        this.getBudgetExplainNumber();
        if (this.state.approve) {
          let info = this.state.info;
          this.getUserCredit(info.applicant.userOID, info.jobId);
          this.setState({showApproveBottom: this.showApproveButton(info.approvalChain, info.approvalChains, this.props.user.userOID, info.status)});
        }
        this.isShowChangedStatus(); //待审批详情是否单据状态已变更
      })
    }).catch(e => {
      this.setState({loading: false});
      let error = e.response.data;
      if (error.validationErrors && error.validationErrors.length) {
        message.error(error.validationErrors[0].message)
      } else {
        message.error(error.message)
      }
    })
  };

  getGiftDeclareDetail = () => {
    if (this.state.info.formCode !== 'SQ008') return ;
    giftDeclareService.getGiftDeclare({ businessCode: this.state.info.businessCode }).then(resOfGift => {
      let giftDeclareValue = resOfGift.data
      // console.log('giftDeclareValue', giftDeclareValue)
      if (!giftDeclareValue) {
        errorMessage(resOfGift)
        return
      }
      if (Array.isArray(giftDeclareValue)) {
        giftDeclareValue = giftDeclareValue[0]
      }
      if (!giftDeclareValue) {
        giftDeclareValue = {}
      }
      this.setState({ giftDeclareValue: setGiftDeclareValue(giftDeclareValue, this, false) });
      return
    }).catch(e => {
      errorMessage(e)
    })
  }

  //员工待审批详情页进来的，但是单据状态不是审批中，需要弹提示语
  isShowChangedStatus = () => {
    const { approving } = this.props.location.query;
    const { approve, info } = this.state;
    if (approving && approve && info.status !== 1002 && !['SQ002', 'SQ003', 'SQ004', 'SQ021', 'SQ022', 'SQ023'].includes(info.formCode)) {
      message.error(messages('request.key677')/*无须审批，单据可能已被他人处理*/);
    }
  };

  //获取第三方返回信息
  getThirdPartyInfo = () => {
    const { info } = this.state;
    const { profile } = this.props;
    if (profile['request.external.info.display']) {
      requestService.getThirdPartyInfo(info.applicationOID).then(res => {
        this.setState({thirdPartyInfo: res.data});
      });
    }
  };

  isShowAmount = () => {
    const { info } = this.state;
    let custFormValues = info.custFormValues;
    let isHasBudgetDetail = false;
    custFormValues && custFormValues.map((valueItem) => {
      if (valueItem.messageKey === 'budget_detail' || valueItem.messageKey === 'public.assembly') {
        isHasBudgetDetail = true;
      }
    });
    this.setState({isHasBudgetDetail});
  };

  getMcdGoingArr = () => {
    const { info: {custFormValues, formCode} } = this.state;
    if (formCode !== 'OFFLINE_FLIGHT_CONFIRMATION_FORM') {
      this.setState({mcdGoingArr: []});
      return;
    }

    let orgGoingArr = [];
    let formattedGoingArr = [];
    const result = {};
    let fligtFrom;
    let fligtTo;
    custFormValues && custFormValues.map(cf => {
      const {fieldCode, value, showValue} = cf;
      if(fieldCode === 'going') {
        orgGoingArr = JSON.parse(value || '[]');
      }else if(fieldCode === 'supplierOrder') { //推送美亚订单号
        result.supplierOrderNo = value;
      }else if(fieldCode === 'orderNo') { //推送甄选订单号 KS00000000
        result.orderNo = value;
      }else if(fieldCode === 'travelNo') { //汇联易申请单号
        result.travelNo = value;
      }else if(fieldCode === 'orderType') { //订单类型
        result.orderType = showValue;
      }else if(fieldCode === 'totalAmount') { //总金额
        result.subOrderTotalAmount = value;
      }else if(fieldCode === 'passenger') { //乘机人
        result.passengerName = value;
      }else if(fieldCode === 'approvalType') { //是否超标
        result.safeBuffer = value === '1';
        result.approvalText = value; // 审批事由
      }else if(fieldCode === 'originPrice') { //原订单金额
        result.originPrice = value;
      }
    });
    const lastIndex = orgGoingArr.length - 1;
    orgGoingArr && orgGoingArr.map((going, index) => {
      const {arrivalAirport, arrivalCity, arrivalDate, cabin, departureAirport, departureCity, departureDate,
        flight = '', meal, planeModel, departureTime, arrivalTime } = going;
      const departureDateArr = departureDate ? departureDate.split(' ') : [];
      const arrivalDateArr = arrivalDate ? arrivalDate.split(' ') : [];
      formattedGoingArr.push({
        airlineName: flight.split(' ')[0],
        flightNo: flight.split(' ')[1],
        departureDate,
        startTime: departureDateArr[1] || departureTime,
        departureCityName: departureCity,
        departureAirportName: departureAirport,
        arrivalDate,
        endTime: arrivalDateArr[1] || arrivalTime,
        arrivalCityName: arrivalCity,
        arrivalAirportName: arrivalAirport,
        planeModel,
        cabinClassName: cabin,
        meal,
        // seatClass: `${planeModel} | ${cabin} | ${meal}`,
        isDateText: true,
        hideTag:true
      });

      index === 0 && (fligtFrom = departureCity);
      index === lastIndex && (fligtTo = arrivalCity);
    });
    result.journeys = formattedGoingArr;
    result.hideTag = true;
    result.isOfflineOrder = true;
    this.setState({mcdGoingArr: [result], fligtFrom, fligtTo});
  }

  getMcdHotelArr = () => {
    const { info: {custFormValues, formCode} } = this.state;
    if (formCode !== 'OFFLINE_HOTEL_CONFIRMATION_FORM') {
      this.setState({mcdHotelArr: []});
      return;
    }

    let temp = {};
    let hotelFromDate;
    let hotelToDate;
    custFormValues && custFormValues.map((cf) => {
      const {fieldCode, value, showValue} = cf;
      switch (fieldCode) {
        case 'HOTEL_NAME':
          temp['hotelName'] = value;
          break;
        case 'STAR':
          temp['star'] = value;
          break;
        case 'FROM_DATE':
          hotelFromDate = temp['startTime'] = value;
          break;
        case 'LEAVE_DATE':
          hotelToDate = temp['endTime'] = value;
          break;
        case 'passenger':
          temp['clientNames'] = value;
          break;
        case 'HOTEL_STAYS':
          temp['day'] = value;
          break;
        case 'ROOM_NUMBER':
          temp['roomCount'] = value;
          break;
        case 'ROOM_TYPE':
          temp['roomTypeName'] = value;
          break;
        case 'HOTEL_UNIT_PRICE':
          temp['totalAmount'] = value;
          break;
        case 'travelNo': //汇联易申请单号
          temp['travelNo'] = value;
          break;
        case 'orderType': //订单类型
          temp['orderType'] = showValue;
          break;
        case 'supplierOrder': //供应商订单号
          temp['tmcOrderID'] = value;
          break;
        case 'orderNo': //甄选订单号
          temp['orderId'] = value;
          break;
        case 'approvalType': //是否超标
          // case 'overstepBufferReason': //buffer判断理由
          temp['safeBuffer'] = value === '1';
          temp['approvalText'] = value; // 审批事由
          break;
        case 'CITY_NAME': //城市
          temp['cityName'] = value;
          break;
        case 'originPrice': //原订单价格
          temp['originPrice'] = value;
          break;
      }
    });

    temp.hideTag = true;
    // temp.isDateText = true;
    temp.isOfflineOrder = true;
    this.setState({mcdHotelArr: [temp], cityName: temp.cityName, hotelFromDate, hotelToDate});
  }

  //获取机酒确认单下所有订单
  handleOrderList = () => {
    const { info: {custFormValues} } = this.state;
    const result = {};
    custFormValues && custFormValues.map(cf => {
      const {fieldCode, value} = cf;
      if(fieldCode === 'orderNo') { //甄选订单号 即Kxxxxx或KSxxxxx
        result.orderNo = value;
      }else if(fieldCode === 'travelNo') { //原申请单号
        result.travelNo = value;
      }else if(fieldCode === 'supplierOrder') { //推送美亚订单号 TBXXX
        result.supplierOrder = value;
      }
    });
    this.setState({mcdFieldValue: result});
    requestService.getAllOrderList({businessCode: result.travelNo, tenantId: this.props.user.tenantId || this.props.tenant.id}).then(res => {
      if (res.data.success) {
        this.setState({
          flightOrderList: res.data.body.flightOrderList,
          hotelOrderList: res.data.body.hotelOrderList
        },() => {
          if (this.state.info.formCode === 'OFFLINE_FLIGHT_CONFIRMATION_FORM') {
            this.handleFlightOrderList();
          }else if (this.state.info.formCode === 'OFFLINE_HOTEL_CONFIRMATION_FORM') {
            this.handleHotelOrderList();
          }
        })
      }else {
        console.log("获取所有订单失败")
        message.error(res.data.message)
      }
    }).catch(e => {
      console.log(e)
    })
  }

  //获取机票确认单原甄选订单号
  handleFlightOrderList = () => {
    const { flightOrderList,mcdFieldValue } =this.state;
    const { supplierOrder } = mcdFieldValue;
    // if (mcdFieldValue.orderNo.indexOf('KS') > -1) {
    //   console.log("寻找子订单---------")
    //   flightOrderList.map(first => {
    //     first.subOrderList.map(sub => {
    //       if (sub.subCustomerOrderId === mcdFieldValue.orderNo) {
    //         this.handleFlightSubOrderList(sub.beforeChangeSubCustomerOrderId);
    //       }
    //     })
    //   })
    // }else {
    //   console.log("寻找主订单-----------")
    //   flightOrderList.map(first => {
    //     if (first.mainOrder.customerOrderId === mcdFieldValue.orderNo) {
    //       flightOrderList.map(second => {
    //         const{mainOrder,journeyList} = second;
    //         if (mainOrder.customerOrderId === first.mainOrder.beforeChangeCustomerOrderId){
    //           this.setState({flightOriginjourneyList: journeyList});
    //         }
    //       })
    //     }
    //   })
    // }
    console.log("根据美亚订单号寻找子订单---------")
    flightOrderList.map(first => {
      first.subOrderList.map(sub => {
        if (sub.supplierOrderNo === supplierOrder) {
          this.handleFlightSubOrderList(sub.beforeChangeSubCustomerOrderId);
        }
      });
    });
  }

  //处理子订单
  handleFlightSubOrderList = (beforeOrderId) => {
    const { flightOrderList } =this.state;
    let flightOriginjourneyList = [];
    flightOrderList.map(second => {
      second.subOrderList.map(sub => {
        if (sub.subCustomerOrderId === beforeOrderId) {
          const journeyIds = sub.journeyId.split('_');
          console.log('---原订单的journeyIds---')
          second.journeyList.map(journey => {
            (journeyIds.includes(String(journey.journeyId))) && flightOriginjourneyList.push(journey);
          });
        }
      })
    })
    this.setState({flightOriginjourneyList});
  }

  //获取酒店确认单原甄选订单号
  handleHotelOrderList = () => {
    const { hotelOrderList,mcdFieldValue } =this.state;
    hotelOrderList.map(first => {
      if (first.heliosOrderID === mcdFieldValue.orderNo) {
        hotelOrderList.map(second => {
          if (second.heliosOrderID === first.heliosOriginalOrderID){
            this.setState({hotelOriginjourneyList: second});
          }
        })
      }
    })
  }

  //获取天数差
  getDifferDays = (sDate, eDate) => {
    sDate = new Date(new Date(sDate).format('yyyy-MM-dd'));
    eDate = new Date(new Date(eDate).format('yyyy-MM-dd'));
    return Math.abs(Math.floor((eDate - sDate)/1000/60/60/24)) + 1
  };

  getIfValidDuring = (sDate, eDate) => {
    return new Date(sDate).getTime() <= new Date(eDate).getTime();
  };

  //获取星期几
  getWeed = (value) => {
    switch(value) {
      case 0:
        return messages('request.key33'/*周日*/);
      case 1:
        return messages('request.key34'/*周一*/);
      case 2:
        return messages('request.key35'/*周二*/);
      case 3:
        return messages('request.key36'/*周三*/);
      case 4:
        return messages('request.key37'/*周四*/);
      case 5:
        return messages('request.key38'/*周五*/);
      case 6:
        return messages('request.key39'/*周六*/);
    }
  };

  //获取预算执行结果数量
  getBudgetExplainNumber = () => {
    const { info } = this.state;
    let params = {
      applicationOID: info.applicationOID
    };
    requestService.getBudgetExplain(params).then(res => {
      this.setState({
        budgetExplainNumber: Number(res.data || 0)
      })
    });
  };

  //判断是否显示底部审批／驳回等按钮
  showApproveButton = (approvalChain, approvalChains, currentUserId, status) => {
    let showBottom = false;
    if(status!==1002){
      return;
    }
    if(approvalChain){
      if(approvalChain.approverOID == currentUserId){
        showBottom = true;
      }
    }
    if(approvalChains){
      approvalChains.forEach((approver) => {
        if(approver.approverOID == currentUserId){
          showBottom = true;
        }else{
          if(approver.proxyApproverOIDs){
            approver.proxyApproverOIDs.forEach((proxyApprover) => {
              if(proxyApprover == currentUserId){
                showBottom = true;
              }
            })
          }
        }
      })
    }
    return showBottom;
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { info } = this.state;
    let showHangUp = false;
    let approverOID = getQueryUrlParam('approverOID');
    info.approvalChains && info.approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  //获取信用分
  getUserCredit = (applicantOID, jobId)=>{
    requestService.getUserCredit(applicantOID, jobId)
      .then(res=>{
        this.setState({
          creditInfo: res.data,
        })
      })
  };

  //查看信用详情
  handleCredit = (e) => {
    //待开发
    e.stopPropagation();
    this.setState({honestModalShow: true});
  };

  //申请单信息／审批进度 切换
  handleTabsChange = (tab) => {
    this.setState({ tapValue: tab })
    if (tab === 'requestInfo' && window.ISIE9 && this.props.params.pageFrom === 'closeList') {
      window.location.reload();
    }
  };

  //申请单详情／还款进度 切换
  handleSubTabsChange = (value) => {
    this.setState({ subTabValue: value })
  };

  //借款申请单 - 新建还款
  toRepayment = () => {
    this.setState({
      subTabValue: 'repayment',
      showNewRepaymentSlide: true
    })
  };

  //借款申请单 - 新建还款
  handleRepaymentSave = () => {
    this.setState({ showNewRepaymentSlide: false },() => {
      this.getInfo()
    })
  };

  //格式化money
  renderMoney = (value) => {
    let numberString = Number(value || 0).toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
    numberString += (numberString.indexOf('.') > -1 ? '' : '.00');
    return numberString
  };
  //获取申请单查看来源
  getRequestReportFrom = () => {
    const {pageFrom} = this.props.params;
    if (pageFrom === 'my') {
      return 'myView';
    }
    if (~this.props.location.pathname.indexOf('financial-management')) {
      return 'auditView';
    }
    return 'approveView'
  };

  //预览表单二维码
  renderPreviewQCode = () => {
    const { applicationOID } = this.props.params;
    let qrcodeValue = `https://www.huilianyi.com/miniprogram/?applicationOID=${applicationOID}&baseURL=${window.location.origin}`;
    return (
      <div>
        <div style={{textAlign: "center", marginBottom: 6}}>{messages('request.key602')/*微信扫一扫转发*/}</div>
        <QrCode
          value={qrcodeValue}
          renderAs={"svg"}
          fgColor={"#000000"}
          size={100}
        />
      </div>
    )
  };

  goToOldDetail = () => {
    const { requestDetail, info } = this.state;
    const { myAvailReqForms = [] } = this.props;
    const {parentApplicationOID, parentApplicationFormOID} = info;
    // let targetFormOID = '';
    // myAvailReqForms && myAvailReqForms.map(item => {
    //   const {formName, formOID} = item;
    //   formName === '' && (targetFormOID = formOID);
    // })
    console.log('----myAvailReqForms----', myAvailReqForms, parentApplicationOID, parentApplicationFormOID)
    let url = requestDetail.url.replace(':formOID', parentApplicationFormOID).replace(':applicationOID', parentApplicationOID) + '?from=request';
    if (window.ISIE9) {
      url = `#${url}`;
    }
    window.open(url);
  };

  //催办
  handelApprovePress = () =>{
    let entity = this.props.entities
    const {info} = this.state;
    const {approverOID, entityOID, entityType} = info.approvalChains[0];
    const { applicantOID, businessCode, formOID } = info
    this.setState({ disablePress:true });
    let params ={
      approverOID,
      entityOID,
      entityType,
      applicantOID,
      businessCode,
      formOID
    }
    adminApproveListService.postPressMessage(params)
      .then(res=>{
        if(res.data){
          message.info(messages('components.key746')/*已向审批人发出催办消息*/);
          setTimeout(() => {
            // dataSource[index].hasClicked = false;
            this.setState({ disablePress:false })
          }, 3000)
        }
      }).catch(e => {
      this.setState({ disablePress:false })
      // this.setState({loading: false});
      message.error(`${e.response.data.message}`)
    });
  };

  isCallBack = (isChange) => {
    this.setState({
      [isChange.code]: isChange[isChange.code]
    }, () => {
      this.getInfo()
    })
  }

  /**
   * 公共列表配置以后审核页面要显示明细
   * @see https://pmo.mcd.com.cn/jira/browse/TES-805
   * #746里有特殊处理逻辑，这个逻辑需要保留。保留后的逻辑如下：
   * 如果是商务应酬申请单（SQ001），那么先调用
   * `/api/application/getIsHideParticipantsList?applicationOID=${OID}`
   * 接口判断是会否需要隐藏参与人清单。如果隐藏，
   * 那么这个申请单下的所有公共列表均不展示；如果展示，则正常走#805的逻辑。
   */
  updateUnifiedTableList = () => {
    const { applicationOID } = this.props.params;
    const { info, formInfo } = this.state;
    const fieldMap = {};
    const formFieldDetail = [
      {columnComment:messages("budget-detail.key1")/*费用类型*/,columnName:"name",widgetType:0,visible:1},
      {columnComment:messages('budget-detail.key2')/*币种*/,columnName:"currencyCode",widgetType:0,visible:1},
      {columnComment:messages('budget-detail.key3')/*金额*/,columnName:"baseCurrencyAmount",widgetType:1,visible:1},
      {columnComment:messages('budget-detail.key4')/*汇率*/,columnName:"companyCurrencyRate",widgetType:1,visible:1},
      {columnComment:messages('budget-detail.key5')/*备注*/,columnName:"remark",widgetType:0,visible:1, showTooltip: true}
    ]
    //罚款及滞纳金支付申请单，未通过TMC购买国内机票申请,私车公用未使用里程补贴申请,
    //餐厅紧急情况下购可乐、水等食品对外销售等申请需要展示金额
    if(['SQ001','SQ009','SQ013','SQ015','SQ016'].includes(info.formCode)){
      formInfo.customFormFields.forEach((field) => {
        if (field.messageKey === "public.assembly") {
          if (!fieldMap[field.fieldOID]) {
            fieldMap[field.fieldOID] = {
              fieldOID: field.fieldOID,
            };
          }
          fieldMap[field.fieldOID].fieldName = field.fieldName;
          fieldMap[field.fieldOID].formField = field.formField;
        }
        if (field.messageKey === "budget_detail" && field.value !==null) {
          if (!fieldMap[field.fieldOID]) {
            fieldMap[field.fieldOID] = {
              fieldOID: field.fieldOID,
            };
          }
          fieldMap[field.fieldOID].fieldName = field.fieldName;
          fieldMap[field.fieldOID].formField = JSON.stringify(formFieldDetail);
          fieldMap[field.fieldOID].value = field.value;
        }
      });
      info.custFormValues.forEach((item) => {
        if (item.messageKey === "public.assembly") {
          if (!fieldMap[item.fieldOID]) {
            fieldMap[item.fieldOID] = {
              fieldOID: item.fieldOID,
            };
          }
          fieldMap[item.fieldOID].value = item.value;

        }
         if (item.messageKey === "budget_detail" && item.value !==null) {
          if (!fieldMap[item.fieldOID]) {
            fieldMap[item.fieldOID] = {
              fieldOID: item.fieldOID,
            };
          }
          fieldMap[item.fieldOID].fieldName = item.fieldName;
          fieldMap[item.fieldOID].formField = JSON.stringify(formFieldDetail);
          fieldMap[item.fieldOID].value = item.value;
          fieldMap[item.fieldOID].messageKey = item.messageKey;
        }
      });
    }else{
      formInfo.customFormFields.forEach((field) => {
        if (field.messageKey === "public.assembly") {
          if (!fieldMap[field.fieldOID]) {
            fieldMap[field.fieldOID] = {
              fieldOID: field.fieldOID,
            };
          }
          fieldMap[field.fieldOID].fieldName = field.fieldName;
          fieldMap[field.fieldOID].formField = field.formField;
        }
      });
      info.custFormValues.forEach((item) => {
        if (item.messageKey === "public.assembly") {
          // console.log('item', item)
          if (!fieldMap[item.fieldOID]) {
            fieldMap[item.fieldOID] = {
              fieldOID: item.fieldOID,
            };
          }
          fieldMap[item.fieldOID].value = item.value;
        }
      });
    }
    const unifiedTableList = Object.values(fieldMap);
    unifiedTableList.map(item =>{
      if(item.messageKey === "budget_detail"){
        let value = JSON.parse(item.value).budgetDetail
        if(value.length > 1){
          value.map((item)=>{
            item.value += item;
          })
        }
        item.value = JSON.stringify(value);
      }
    })
    // 商务应酬申请审批通过6个月后，参与人清单自动隐藏
    // https://pmo.mcd.com.cn/jira/browse/TES-746
    if (info.formCode === "SQ001") {
      let list = [];
      JSON.parse(unifiedTableList[0].formField).map(item => {
        if (item.columnName === 'custom_enumeration_item_oid') {
          if (info.status === 1002 || info.status === 1001) {
            list.push(true)
          } else {
            list.push(false)
          }
        } else {
          list.push(false)
        }
      });
      requestService.getIsHideParticipantsList(applicationOID).then((res) => {
        let isHide = res.data;
        if (!isHide) {
          this.setState({
            unifiedTableList,
            SQ001readOnly: list
          });
        } else {
          let arr = [];
          unifiedTableList.map(item => {
            if (item.fieldName !== '参与人清单') {
              arr.push(item)
            }
          })
          this.setState({
            unifiedTableList: arr,
            SQ001readOnly: list
          });
        }
      });
    } else {
      this.setState({
        unifiedTableList,
      });
    }
  };

  onSubmit = () => {
    const { info } = this.state
    let custFormValues = info.custFormValues
    let custFormValuesJson = {}
    custFormValues && custFormValues.map(item => {
      custFormValuesJson[item.fieldCode] = item
    })
    let giftReceiverDTOs = this.childR ? this.childR.state.dataR : []
    let dataA = this.childA ? this.childA.state.dataA : []
    let dataB = this.childB ? this.childB.state.dataB : []
    let dataC = this.childC ? this.childC.state.dataC : []
    let dataD = this.childD ? this.childD.state.dataD : []
    let giftLineDTOs = [
      ...dataA,
      ...dataB,
      ...dataC,
      ...dataD
    ]
    info.giftApplication = {
      applicationOID: info.applicationOID,
      baseCurrencyAmount: info.totalAmount,
      businessCode: info.businessCode,
      companyCurrencyRate: 1,
      currencyCode: info.currencyCode,
      costCenterItemCode: custFormValuesJson.costcenter ? custFormValuesJson.costcenter.valueCode : '',
      costCenterItemName: custFormValuesJson.costcenter ? custFormValuesJson.costcenter.showValue : '',
      costCenterItemOID: custFormValuesJson.costcenter ? custFormValuesJson.costcenter.value : '',
      externalParticipantNumber: 0,
      externalParticipants: [],
      participantNum: 0,
      totalBudget: info.totalAmount,
      totalSubsidiesBudget: 0,
      expenseConfirmer: '',
      recipientsNum: custFormValuesJson.number ? custFormValuesJson.number.showValue : '',
      employeeId: info.applicant.employeeID,
      isDeleted: false,
      custFormValues,
      giftReceiverDTOs,
      giftLineDTOs
    }
    this.setState({submitLoading: true}, () => {
      requestService.giftRequestDetailTableSubmit(info).then(res => {
        this.setState({submitLoading: false})
        message.success(messages('request.key197'/*提交成功*/))
        // const returnUrl = this.props.location.pathname.split('/')[2]
        // this.context.router.push(menuRoute.getRouteItem(returnUrl,'key').url)
        menuRoute.goBack(this)
      }).catch(() => {
        this.setState({submitLoading: false})
      })
    })
  }

  onHandleSign =()=>{
    let infoData = this.state.info
    this.setState({signLoading : true});
    let lineDTOS =  infoData.giftApplication.giftLineDTOs;
    let valid = false;
    if(lineDTOS.length==0){
      message.warning('缺少礼品行');
      this.setState({signLoading : false});
      return;
    }
    lineDTOS = lineDTOS.filter(i=> i.distributionStatus == '已发货' && i.signingStatus == '待签收')
    try {
      lineDTOS.forEach(i => {
        if(i.distributionStatus != '已发货'){
          valid =true;
          message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}未发货`);
          throw Error();
        }
        if(i.signingStatus != '待签收'){
          valid =true;
          message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}${i.signingStatus}`);
          throw Error();
        }
      })
    } catch(e){
    }
    if(valid){
      this.setState({signLoading : false});
      return;
    }
    let data = [];
    lineDTOS.forEach(i => {
      let item = {
        businessCode: i.lineNo.split('-')[0],
        lineCode: i.lineNo,
        state: 'hand_signed',
      }
      data.push(item);
    })
    httpFetch.post(`${config.baseUrl}/api/bath/send/ecs/active?roleType=TENANT`, data).then(res => {
      if(res.data.success){
        message.success('卡券激活成功');
        this.getInfo();
        this.onHandleConfirm();
        this.setState({signLoading : false});
      }else{
        message.error(`卡券激活失败，请稍后重试`)
        this.setState({signLoading : false});
      }
    }).catch((e) => {
      this.setState({signLoading: false})
      errorMessage(e.response);
    })
  }

  onHandleLose =()=>{
    let infoData = this.state.info
    this.setState({loseLoading : true});
    let lineDTOS =  infoData.giftApplication.giftLineDTOs;
    let valid = false;
    if(lineDTOS.length==0){
      message.warning('缺少礼品行');
      this.setState({loseLoading : false});
      return;
    }
    lineDTOS = lineDTOS.filter(i=> i.distributionStatus == '已发货' && i.signingStatus == '待签收')
    try {
      lineDTOS.forEach(i => {
        if(i.distributionStatus != '已发货'){
          valid =true;
          message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}未发货`);
          throw Error();
        }
        if(i.signingStatus != '待签收'){
          valid =true;
          message.warning(`${i.formType==2 ? '礼品卡' : i.formType==3 ? 'BOG' : '现金券'}${i.type}${i.signingStatus}`);
          throw Error();
        }
      })
    } catch(e){
    }
    if(valid){
      this.setState({loseLoading : false});
      return;
    }
    let data = [];
    lineDTOS.forEach(i => {
      let item = {
        businessCode: i.lineNo.split('-')[0],
        lineCode: i.lineNo,
        state: 'hand_lost',
      }
      data.push(item);
    })
    httpFetch.post(`${config.baseUrl}/api/bath/send/ecs/invalid?roleType=TENANT`, data).then(res => {
      if(res.data.success){
        message.success('卡券作废成功');
        this.getInfo()
        this.onHandleConfirm();
        this.setState({loseLoading : false});
      }else{
        message.error(`卡券作废失败，请稍后重试`)
        this.setState({loseLoading : false});
      }
    }).catch((e) => {
      this.setState({loseLoading: false})
      errorMessage(e.response);
    })
  }

  onHandleConfirm =()=>{
    let infoData = this.state.info;
    let type = 'pass';
    let entities = [];
    let item = JSON.stringify({
      approverOID: infoData.approvalChain.approverOID,
      entityOID: infoData.approvalChain.entityOID,
      entityType: infoData.approvalChain.entityType,
    });
    entities.push(JSON.parse(item))
    let params = {
      entities,
    };
    this.setState({confLoading: true});
    approveService[type === 'pass' ? 'handleRequestApprovePass' : 'handleRequestApproveReject'](params).then(res => {
      if (res.status === 200) {
        this.setState({confLoading : false});
        message.success("确认成功");
        menuRoute.goBack(this);
      }
    }).catch(e => {
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
      this.setState({confLoading : false});
    })
  }

  render() {
    let { giftA, giftB, giftC, receiver, unifiedTableList, submitLoading } = this.state;
    const backUrlKey = getQueryUrlParam('backUrlKey')
    const isDoneApproved = getQueryUrlParam('isDoneApproved')
    const { applicationOID, formOID, pageFrom } = this.props.params;
    const { approving, isPreVersion, latestApplicationOID, from, readOnly: readOnlyFromUrl } = this.props.location.query;
    const { payProcess, loading, tapValue, subTabValue, formType, formInfo, showNewRepaymentSlide, info, approvalHistory,
      approve, audit, view, loanRefund, rescheduleRefund, price, readOnly , buttonRoleSwitch, confirmPay, showApproveBottom ,
      adminApprove, costApplication, creditInfo, budgetExplainNumber, isHasBudgetDetail, thirdPartyInfo, mcdHotelArr, mcdGoingArr,
      fligtFrom, fligtTo, cityName, hotelFromDate, hotelToDate, flightOriginjourneyList, hotelOriginjourneyList, SQ001readOnly,signLoading,loseLoading, confLoading
    } = this.state;
    let {formCode} = info;
    let applicant = info.applicant || {}; //申请人信息
    let custFormValues = info.custFormValues || []; //自定义表单
    let type = ''
    custFormValues && custFormValues.map(item => {
      if (item.fieldCode === 'custlist') {
        type = item.valueCode
      }
    })
    let custFormValuesJson = {}
    custFormValues && custFormValues.map(item => {
      custFormValuesJson[item.fieldCode] = item.showValue
      if (item.fieldCode === "company") {
        custFormValuesJson[item.fieldCode] = item.valueCode
      }
    })
    const typeKq =  custFormValuesJson.kq ? custFormValuesJson.kq: ''//卡券类型
    const fafangleixing =  custFormValuesJson.fafangleixing ? custFormValuesJson.fafangleixing: ''//发放类型
    let { nodeName } = this.props.location.query
    const showQrCode = info.status === 1002 && formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['travel.application.share.image'] && JSON.parse(formInfo.customFormPropertyMap['travel.application.share.image']).enabled;
    custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
    let rescheduleRefundInfoShow = false; //是否显示退改签信息
    if (formType === 2003) {
      (info.travelOperationRecords || []).map(item => {
        //type：1002（改签）、1003（退票）
        (item.type === 1002 || item.type === 1003) && (rescheduleRefundInfoShow = true)
      })
    }
    let renderCloseDate = null; //（预计）停用日期
    if (info.status === 1003) { //已通过状态停用时间都是获取个人的停用时间
      if (info.applicationParticipant && info.applicationParticipant.closeDate) {
        if (info.applicationParticipant.closed === 1) { //当前单据对于当前操作人是已停用状态
          renderCloseDate = (
            <span className="detail-info">
              {messages('request.key1'/*关闭日期*/)}：
              {moment(info.applicationParticipant.closeDate).format('YYYY-MM-DD')}
            </span>
          )
        } else {
          //在对于人员未关闭时是否显示停用日期以是否有个人的停用日期为准，停用日期一直获取的为个人的停用日期
          renderCloseDate = (
            <span className="detail-info">
              {messages('request.key2'/*预计关闭日期*/)}：
              {moment(info.applicationParticipant.closeDate).format('YYYY-MM-DD')}
            </span>
          )
        }
      }
    } else { //不是已通过状态时，停用时间都是获取的是单据的停用时间，根据单子的属性
      if (info.closeEnabled && info.closeDate) {
        renderCloseDate = (
          <span className="detail-info">
            {messages('request.key2'/*预计停用日期*/)}：
            {moment(info.closeDate).format('YYYY-MM-DD')}
          </span>
        )
      }
    }
    //将是否是管理员添加进去
    info.admin = this.state.adminApprove;
    //计算总金额
    //不考虑停用单据totalAmount为0的情况了，bug21199
    let totalAmount = this.filterMoney(info.totalAmount || 0, queryCurrencyPrecision(info.currencyCode), true);
    let warningList = info.warningList ? JSON.parse(info.warningList) : null;
    let qrCode = <div style={{position: "absolute", right: 20, top: 0, zIndex: 3, fontSize: 22, cursor: "pointer"}}>
      <Popover
        content={this.renderPreviewQCode()}
        trigger="click"
        placement="left"
        getPopupContainer={(triggerNode) => triggerNode.parentNode}
      >
        <Icon type="qrcode" />
      </Popover>
    </div>;
    // 处理warningList中的换行
    let ind;
    if (warningList) {
      warningList.map((w, index) => {
        if (w.externalPropertyName === '9003') {
          if (pageFrom === 'my') { //非审批的单据，隐藏日期重复标签
            ind = index;
          } else if (typeof w.message === 'string') {
            w.message = (<div>
              {w.message.split('﹤br/﹥').map(e => (<p>{e}</p>))}
            </div>);
          }
        }
      });
      warningList[ind] && warningList.splice(ind, 1);
    }
    let showUrgeBtn = [1002].includes(Number(info.status || 0)); // 只有状态为“审批中”的单据需要展示催办按钮
    let offlineFlight = info.formCode === 'OFFLINE_FLIGHT_CONFIRMATION_FORM';//机票确认单
    let offlineHotel = info.formCode === 'OFFLINE_HOTEL_CONFIRMATION_FORM';//酒店确认单
    let flightJourneyText = '';
    flightOriginjourneyList.forEach(trip => {
      flightJourneyText += `${moment(trip.departureDate).format('YYYY-MM-DD')} 从${trip.departureCityName}到${trip.arrivalCityName}的航班${trip.flightNo}，`
    })
    let hotelJourneyText = '';
    hotelJourneyText = `${moment(hotelOriginjourneyList.checkInDate).format('YYYY-MM-DD')}到${moment(hotelOriginjourneyList.checkOutDate).format('YYYY-MM-DD')} ${hotelOriginjourneyList.cityName}的酒店 ${hotelOriginjourneyList.hotelName}，`
    let requestInfo = (
      <Spin spinning={loading}>
        {
          ['SQ002', 'SQ003', 'SQ004', 'SQ021', 'SQ022', 'SQ023'].includes(formCode) ? (<div className="top-info">
          <Row className="row-container">
            <span className="top-info-name">{applicant.fullName}</span>
            <span className="detail-info">
              {messages('request.key3'/*工号*/)}：{applicant.employeeID}
              <span className="ant-divider"/>
              {messages('request.key4'/*部门*/)}：{applicant.departmentName || '-'}
              <span className="ant-divider"/>
              {messages('common.user.company')/*员工公司*/}：{applicant.companyName || '-'}
            </span>
          </Row>
          <Row className="row-container">
            <span className="detail-info detail-info-first">{info.formName}：{info.businessCode}</span>
            <span className="detail-info">
              {messages('request.key5'/*提交日期*/)}：{moment(info.submittedDate).format('YYYY-MM-DD')}
            </span>
            <span className="detail-info">
              {messages('request.key6'/*当前状态*/)}：
              {(info.closed || info.participantClosed || (info.applicationParticipant && info.applicationParticipant.closed === 1)) ?
                messages('request.key7'/*已关闭*/) : (
                  constants.getTextByValue(String(info.status + '' + info.rejectType), 'documentStatus') ||
                  constants.getTextByValue(String(info.status + '' + info.type), 'documentStatus') ||
                  constants.getTextByValue(String(info.status), 'documentStatus')
                )
              }
            </span>
          </Row>
          <Row className="row-container">
            <span className="amount">
              {messages('request.key9'/*总金额*/)}：{info.currencyCode} {totalAmount}
            </span>
          </Row>
        </div>) : (<div className="top-info">
          {formType === 2004 && <JDErrorAlert info={info}/>}
          {formType === 2003 && !readOnly && <BookerInfoAlert info={info}/>}
          {warningList && (
            warningList.map((warning, index) => (
              <Alert message={warning.title}
                     description={warning.message ? warning.message : '--'}
                     banner
                     type={warning.type === 0 ? 'warning' : 'error'}
                     key={index}/>
            ))
          )}
          {thirdPartyInfo.code === 'SUCCESS' && thirdPartyInfo.body && (
            <Alert
              style={{margin: '10px 0'}}
              message={messages('request.key645',{arg1: thirdPartyInfo.body})/*提示信息：{arg1}*/}
              type="info"
              showIcon
            />
          )}
          <Row className="row-container">
            <span className="top-info-name">{applicant.fullName}</span>
            <span className="detail-info">
              {(approve || info.admin) && (creditInfo.score || creditInfo.creditRank) &&
              <span className='default-color-font' style={{cursor:'pointer'}} onClick={this.handleCredit}> {messages('request.key524')/*信用分*/}：
                {creditInfo.score || messages('request.key525')/*暂未设置*/}| {messages('request.key526')/*信用等级*/}：{creditInfo.creditRank || messages('request.key525')/*暂未设置*/} >
              </span>
              }
              {messages('request.key3'/*工号*/)}：{applicant.employeeID}
              <span className="ant-divider"/>
              {messages('request.key4'/*部门*/)}：{applicant.departmentName || '-'}
              <span className="ant-divider"/>
              {messages('common.user.company')/*员工公司*/}：{applicant.companyName || '-'}
            </span>
          </Row>
          <Row className="row-container">
            <span className="detail-info detail-info-first">{info.formName}：{info.businessCode}</span>
            <span className="detail-info">
              {messages('request.key5'/*提交日期*/)}：{moment(info.submittedDate).format('YYYY-MM-DD')}
              {info.submittedBy && applicant.userOID !== info.submittedBy &&
                `，${messages('request.key447',{arg1: info.submittedName}/*由 {arg1} 代提*/)}`}
            </span>
            {renderCloseDate}
            <span className="detail-info">{messages('request.key6'/*当前状态*/)}：
              {(info.closed || info.participantClosed || (info.applicationParticipant && info.applicationParticipant.closed === 1)) ?
                messages('request.key7'/*已关闭*/) : (
                  constants.getTextByValue(String(info.status + '' + info.rejectType), 'documentStatus') ||
                  constants.getTextByValue(String(info.status + '' + info.type), 'documentStatus') ||
                  constants.getTextByValue(String(info.status), 'documentStatus')
                )
              }
            </span>
            {info.uniformReimbursementClerk && (
              <span className="detail-info">
                <span className="transfer-tag">{messages('request.key547')/*已转交*/}</span>
                <span style={{color: '#666', marginLeft: 5}}>{info.uniformReimbursementClerk.fullName}</span>
              </span>
            )}
            {this.isShowHangUp() && (
              <Tag style={{marginLeft: 8}} color="#505564">{messages('request.key572')/*暂挂*/}</Tag>
            )}
            <TravelPreviousVersion info={info} isPreVersion={isPreVersion}/>
          </Row>
          <div className="buffer-tip-wrapper">
            {((mcdGoingArr[0] && mcdGoingArr[0].safeBuffer) || (mcdHotelArr[0] && mcdHotelArr[0].safeBuffer)) &&
            <Alert description={messages('mcd.offline.success')}
                   banner
                   type='success'/>}
            {((mcdGoingArr[0] && !mcdGoingArr[0].safeBuffer) || (mcdHotelArr[0] && !mcdHotelArr[0].safeBuffer)) &&
            <Alert description={messages('mcd.offline.fail')}
                   banner
                   type='error'/>}
            {/*task#45605：机票、酒店确认单前端显示调整2.0*/}
            { offlineFlight && (mcdGoingArr[0] && mcdGoingArr[0].approvalText === '2') && flightOriginjourneyList &&
              <span style={{lineHeight: '25px'}}>{messages('mcd.approvalText')}{flightJourneyText}{messages('mcd.approvalText.flight2',{originPrice: this.filterMoney(mcdGoingArr[0].originPrice, 2, true)})}</span>
            }
            { offlineFlight && (mcdGoingArr[0] && mcdGoingArr[0].approvalText === '3') &&
            <span style={{lineHeight: '25px'}}>{messages('mcd.approvalText.flight3', {departureDate: moment(mcdGoingArr[0].journeys[0].departureDate).format('YYYY-MM-DD'), departureCityName: mcdGoingArr[0].journeys[0].departureCityName, arrivalCityName: mcdGoingArr[0].journeys[0].arrivalCityName, flightNo: mcdGoingArr[0].journeys[0].flightNo, originPrice: this.filterMoney(mcdGoingArr[0].originPrice, 2, true)})}</span>
            }
            { offlineHotel && (mcdHotelArr[0] && mcdHotelArr[0].approvalText === '2') &&
            <span style={{lineHeight: '25px'}}>{messages('mcd.approvalText')}{hotelJourneyText}{messages('mcd.approvalText.hotel2', {originPrice: this.filterMoney(mcdHotelArr[0].originPrice, 2, true)})}</span>
            }
          </div>
          <div className="loan-related-application">
            {mcdGoingArr[0] && mcdGoingArr[0].travelNo && (
              <div className="row-container">
                {/*<Icon type="link" className="link-icon"/>*/}
                <a onClick={this.goToOldDetail} style={{fontSize: 16}}>{messages('mcd.old.business.code'/*原申请单号*/)}：{mcdGoingArr[0].travelNo}</a>
              </div>
            )}
          </div>
          <div className="loan-related-application">
            {mcdHotelArr[0] && mcdHotelArr[0].travelNo && (
              <div className="row-container">
                {/*<Icon type="link" className="link-icon"/>*/}
                <a onClick={this.goToOldDetail} style={{fontSize: 16}}>{messages('mcd.old.business.code'/*原申请单号*/)}：{mcdHotelArr[0].travelNo}</a>
              </div>
            )}
          </div>

          <Row className="row-container">
            {isHasBudgetDetail && (
              <span className="amount">
                {messages('request.key9'/*总金额*/)}：
                {info.currencyCode} {totalAmount}
              </span>
            )}
            {formType === 2001 && <TravelDate isLeft={!isHasBudgetDetail} info={info}/>}
          </Row>
          {info && info.loanBillOID && <LoanRelatedApplication info={info} isAutoLoan />}
          {info && info.applicationOID && <RelatedShowList info={info} />}
          {formType === 2001 && showQrCode && qrCode}
        </div>)
        }
      </Spin>
    );
    let signName = customField.getSignNameForSubmitter(formInfo && formInfo.customFormPropertyMap);

    let detailContent = (
      <Spin spinning={loading}>
        <div className="tab-container">
          {!offlineFlight && !offlineHotel &&
          (<h3 className="sub-header-title">{messages('request.key10'/*申请单详情*/)}{!!approving && !readOnlyFromUrl && (
            <ApprovingEdit approvalOID={getQueryUrlParam('approverOID')}
                           entityOID={applicationOID}
                           formOID={formOID}
                           entityType={1001}
                           custFormValues={custFormValues}
                           handleAfterSave={this.getInfo}/>
          )}</h3>)}
          {!offlineFlight && !offlineHotel && customField.renderFields(custFormValues.filter(i=>{
              if((typeKq=== '001' || typeKq=== '实体卡券') && i.fieldCode == 'fafangleixing'){
                return;
              }
              return i;
            }), info, applicant, this.props.params.pageFrom, signName)}
          {/* {formCode === 'SQ017' && <Col span={8} className="field-container">
              <div className="field-name">账本及消费</div>
              <div className="field-content">账本及消费</div>
            </Col>} */}
          {this.props.params.pageFrom === 'closeList' && (
            <Row className="custom-form-row">
              <ExpenseTypeClose info={info} changeHandle={(apportionmentOIDs, budgetOIDs) => {this.setState({apportionmentOIDs: apportionmentOIDs, budgetOIDs: budgetOIDs})}}/>
            </Row>
          )}

          {formCode === 'OFFLINE_HOTEL_CONFIRMATION_FORM' && <Row className="custom-form-row">
              <h3 className={offlineFlight || offlineHotel ? 'offForm-header-title' : 'header-title'}>{messages('request.key14'/*行程信息*/)}</h3>
              <div className="location-off">
                {
                  // this.getIfValidDuring(sDate,item.startTime) && <Tag color="#4B8DFF">
                  //   {messages('request.key464',{arg1: this.getDifferDays(sDate,item.startTime)}/*第 {arg1} 天*/)}
                  //   {' ～ '}
                  //   {messages('request.key464',{arg1: this.getDifferDays(sDate,item.endTime)}/*第 {arg1} 天*/)}
                  // </Tag>
                }
                <span className="date">
                  {new Date(hotelFromDate).format('yyyy.MM.dd')} {this.getWeed(new Date(hotelFromDate).getDay())} ～ {new Date(hotelToDate).format('yyyy.MM.dd')} {this.getWeed(new Date(hotelToDate).getDay())}
                </span>
                <span className="day-and-night">
                  {messages('request.key467',{arg1: this.getDifferDays(hotelFromDate, hotelToDate)}/*{arg1}天*/)}
                  {messages('request.key468',{arg1: this.getDifferDays(hotelFromDate, hotelToDate) - 1}/*{arg1}晚*/)}
                </span>
              </div>
              <div>{messages('request.key337'/*目的地*/)}：{cityName}</div>
            </Row>}
          {formCode === 'OFFLINE_FLIGHT_CONFIRMATION_FORM' && <Row className="custom-form-row">
            <h3 className={offlineFlight || offlineHotel ? 'offForm-header-title' : 'header-title'}>{messages('request.key14'/*行程信息*/)}</h3>
            <Row className="location">
              <Col span={10}>
                <span className="from">{fligtFrom || messages('request.key490')/*不限*/}</span>
                <img src={trafficLineImg}/>
                <span className="to">{fligtTo || messages('request.key490')/*不限*/}</span>
              </Col>
            </Row>
            </Row>}
            {info.formCode === 'OFFLINE_HOTEL_CONFIRMATION_FORM' && <TravelOrderList orderList={mcdHotelArr} type="hotel" isOff={true}/>}
            {info.formCode === 'OFFLINE_FLIGHT_CONFIRMATION_FORM' && <TravelOrderList orderList={mcdGoingArr} type="flight" isOff={true} approvalType={mcdGoingArr[0] && mcdGoingArr[0].approvalText}/>}
            <div >！！！{info.formCode}</div>
            {info.formCode === 'MCD1001' && <div style={{ width: '100%' }}>
              <img src={lowCarbonTravel} style={{ width: '100%', height: 'auto', display: 'block' }} alt="Low Carbon Travel" />
            </div>}
        </div>
        {formType === 2004 && <JDOrderInfo info={info}/>}
      </Spin>
    );
    let valid = true; //签收遗失按钮禁用
    if(info.giftApplication){
        const lineDTOS =  info.giftApplication.giftLineDTOs;
        lineDTOS.forEach(i => {
          if(i.distributionStatus == '已发货' && i.signingStatus == '待签收'){
            valid=false
          }
        })
        lineDTOS.forEach(i => {
          if(i.distributionStatus != '已发货' || i.signingStatus == null){
            valid=true
          }
        })
    }

    let validConf = false; //整单确认按钮禁用
    if(info.giftApplication){
        const lineDTOS =  info.giftApplication.giftLineDTOs;
        lineDTOS.forEach(i => {
          if(!(i.distributionStatus == '已发货' && i.signingStatus != '待签收' && i.signingStatus != null)){
            validConf= true
          }
        })
    }
    custFormValues && custFormValues.map((i,index ) => { //不显示逻辑判断字段
      if (i.fieldCode === 'luojipanduan') {
        custFormValues.splice(index, 1)
      }
    })
    return (
      <div className="base-request-detail background-transparent">
        <div className="tabs-info" style={{position: 'relative'}}>
          <Tabs type="card" activeKey={tapValue} onChange={this.handleTabsChange}>
            <TabPane tab={messages('request.key11'/*申请单信息*/)} key="requestInfo">{requestInfo}</TabPane>
            {budgetExplainNumber > 0 && false && (
              <TabPane tab={messages('request.key584')/*预算执行信息*/} key="budgetExplain">
                <BudgetExplain documentType="EXP_REQUISITION" documentId={info.applicationOID}/>
              </TabPane>
            )}
            <TabPane tab={messages('request.key12'/*审批历史*/)} key="approvals">
              <ApproveHistory approvalChains={info.approvalChains} isShowReply={this.props.params.pageFrom === 'my' && info.status === 1003} businessCode={info.businessCode} approvalHistory={approvalHistory} applicantInfo={applicant} formCode={info.formCode}
                              needApplicantConfirm={info.needApplicantConfirm}/>
            </TabPane>
          </Tabs>
          {!!approving && !readOnlyFromUrl && (showApproveBottom || adminApprove) && (
            <ApproveTag entityOID={this.props.params.applicationOID}/>
          )}
        </div>
        {false && tapValue === 'requestInfo' && (
          <Tabs className="detail-tabs" activeKey={subTabValue} onChange={this.handleSubTabsChange}>
            <TabPane tab={messages('request.key10'/*申请单详情*/)} key="detail">{detailContent}</TabPane>
            {formType === 2001 && this.state.manageType &&(
              <TabPane tab={messages('request.key14'/*行程信息*/)} key="travelInfo">
                <TravelInformation applicationOID={this.props.params.applicationOID}
                                   info={info}
                                   customFormPropertyMap={formInfo.customFormPropertyMap}
                                   controlFields={JSON.parse(formInfo.customFormProperties.controlFields || '{}')}
                                   isPreVersion={isPreVersion === 'true'}
                                   isReadOnly={readOnly}
                                   latestApplicationOID={latestApplicationOID}/>
              </TabPane>
            )}
            {formType === 2001 && !this.state.manageType &&(
              <TabPane tab={messages('request.key14'/*行程信息*/)} key="travelInfo">
                <TravelInformationElement applicationOID={this.props.params.applicationOID}
                                   info={info}
                                   customFormPropertyMap={formInfo.customFormPropertyMap}
                                          isPreVersion={isPreVersion === 'true'}
                                   latestApplicationOID={latestApplicationOID}/>
              </TabPane>
            )}
            {formType === 2003 && rescheduleRefundInfoShow && (
              <TabPane tab={messages('request.key15'/*退改签信息*/)} key="rescheduleRefundInfo">
                <RescheduleRefundInfo info={info}/>
              </TabPane>
            )}
            {formType === 2003 && (info.travelOrders || []).length > 0 && (
              <TabPane tab={messages('request.key16'/*机票信息*/)} key="bookerTicketInfo">
                <BookerTicketInfo info={info}
                                  afterBoardConfirm={() => {this.getInfo(formType)}}/>
              </TabPane>
            )}
          </Tabs>
        )}
        {tapValue === 'requestInfo' && (
          <div data-tab='requestInfo' className="request-info-wrapper" style={{marginBottom: '15px'}}>
            <div className="request-info">
              {detailContent}
            </div>
            {formType === 2001 && this.state.manageType &&(
              <div className="request-info">
                <TravelInformation applicationOID={this.props.params.applicationOID}
                                    info={info}
                                    customFormPropertyMap={formInfo.customFormPropertyMap}
                                    controlFields={JSON.parse(formInfo.customFormProperties.controlFields || '{}')}
                                    isPreVersion={isPreVersion === 'true'}
                                    isReadOnly={readOnly}
                                    latestApplicationOID={latestApplicationOID}
                                    approving={approving}/>
              </div>
            )}
            {formType === 2001 && !this.state.manageType &&(
              <div className="request-info">
                <TravelInformationElement applicationOID={this.props.params.applicationOID}
                                          info={info}
                                          customFormPropertyMap={formInfo.customFormPropertyMap}
                                          isPreVersion={isPreVersion === 'true'}
                                          latestApplicationOID={latestApplicationOID}/>
              </div>
            )}
            {[ 'SQ021', 'SQ023'].includes(formCode) && (
              <div>
                {type === '1' && ['SQ002', 'SQ021'].includes(formCode) && (<GiftRequestDetailA onRef={ref => this.childA = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftRequestDetailA>)}
                <GiftRequestDetailB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftRequestDetailB>
                <GiftRequestDetailC onRef={ref => this.childC = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftRequestDetailC>
                {formCode === 'SQ002' || formCode === 'SQ021' ?(type === '1' && <ReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></ReceiverInformation>) : <ReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></ReceiverInformation>}
              </div>
            )}
            {/* $# 参考实体卡卷修改供应商 */}
            {['SQ004'].includes(formCode) && (
              <div>
                {type === '1' && ['SQ002', 'SQ021'].includes(formCode) && (<GiftRequestA onRef={ref => this.childA = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftRequestA>)}
                <GiftRequestB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} nodeName={nodeName} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved} approve={approve} costApplication={costApplication}></GiftRequestB>
                {/* <GiftRequestC onRef={ref => this.childC = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved} approve={approve} costApplication={costApplication}></GiftRequestC> */}
                <GiftRequestD onRef={ref => this.childD = ref} isCallBack={(isChange) => this.isCallBack(isChange)} nodeName={nodeName} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved} approve={approve} costApplication={costApplication}></GiftRequestD>
                {formCode === 'SQ002' || formCode === 'SQ021' ?(((typeKq === "电子卡券" && fafangleixing === "直发") || (typeKq === "电子卡券" && fafangleixing === "派发" && type === '1') || (typeKq === "实体卡券" && type === '1')) && <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftReceiverInformation>) : <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftReceiverInformation>}
              </div>
            )}
            {['SQ002'].includes(formCode) && (
              <div>
                {type === '1' && ['SQ002', 'SQ021'].includes(formCode) && (<GiftRequestA onRef={ref => this.childA = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftRequestA>)}
                <GiftRequestB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved} approve={approve} costApplication={costApplication}></GiftRequestB>
                {
                  (typeKq !== '电子卡券' || (typeKq === '电子卡券' && custFormValuesJson.company === '104')) && <GiftRequestC onRef={ref => this.childC = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved} approve={approve} costApplication={costApplication}></GiftRequestC>
                }
                <GiftRequestD onRef={ref => this.childD = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved} approve={approve} costApplication={costApplication}></GiftRequestD>
                {formCode === 'SQ002' || formCode === 'SQ021' ?(((typeKq === "电子卡券" && fafangleixing === "直发") || (typeKq === "电子卡券" && fafangleixing === "派发" && type === '1') || (typeKq === "实体卡券" && type === '1')) && <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftReceiverInformation>) : <GiftReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftReceiverInformation>}
              </div>
            )}
            {
              ['SQ003', 'SQ022'].includes(formCode) && <GiftRequestDetailB onRef={ref => this.childB = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></GiftRequestDetailB>
            }
            {
              ['SQ003'].includes(formCode) && <ReceiverInformation onRef={ref => this.childR = ref} isCallBack={(isChange) => this.isCallBack(isChange)} info={info} formOID={formOID} applicationOID={applicationOID} id={info.id} type="detail" isDoneApproved={isDoneApproved}></ReceiverInformation>
            }
            {formCode === 'SQ008' && <GiftDeclareDetail value={this.state.giftDeclareValue}></GiftDeclareDetail>}
            {formCode === 'SQ024' && <GreenCode readonly={true}></GreenCode>}
          </div>
        )}

        {tapValue === 'requestInfo' && unifiedTableList.length > 0 && (
          <div>
            {unifiedTableList.map(tableData => {
              return (
                <div key={tableData.fieldName} data-tab='requestInfo' className="request-info-wrapper" style={{marginBottom: '15px'}}>
                  <div className="request-info">
                    <div className="tab-container">
                      <h3 className="sub-header-title">
                        {tableData.fieldName}
                      </h3>
                    </div>
                    <div>
                      {/* <pre>{JSON.stringify(tableData, null, 2)}</pre> */}
                      <UnifiedTable
                        key={tableData.value}
                        showIndex
                        readonly
                        exportFile={false}
                        importFile={false}
                        cellMinWidth={100}
                        formField={tableData.formField}
                        value={tableData.value}
                        status={info.status}
                        SQ001readOnly={SQ001readOnly}
                        isRemarkRequired={formCode === 'SQ001' ? true : false}
                      ></UnifiedTable>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}

        <div style={{height: '60px'}}></div>

        {audit && (buttonRoleSwitch ?
            <AuditApplicationDetail
              status={info.status}
              entityOID={this.props.params.applicationOID}
              entityType={1001}
              approvalHistory={approvalHistory}
            /> :
            <Affix offsetBottom={0} className='bottom-bar'><GoBackBtn backUrlKey={backUrlKey} backType={this.props.params.backType}/></Affix>
        )}
        {(!readOnly || approve || rescheduleRefund || price || loanRefund || payProcess || confirmPay || view || adminApprove) && nodeName !== '预约领取' && nodeName !== '签收确认' && (
          <Affix offsetBottom={0} className={`bottom-bar ${((approve && approving && showApproveBottom) || (!approve && approving)) ? 'bottom-bar-approve' : ''}`}>
            {!readOnly && <RecallBtn backUrlKey={backUrlKey} info={info} recallEnable={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['formWithdrawAuthority']}/>}
            {!readOnly && showUrgeBtn && <span><Button onClick={this.handelApprovePress}
                                  disabled={this.state.disablePress}
                                  className="notice-btn"
                                  type="primary">{messages('components.key747')/*催办*/}</Button>&nbsp;&nbsp;</span>}
            {/*{(!readOnly || view) && <PrintBtn info={info} printFlag={view}/>}*/}
            {!readOnly && this.props.params.pageFrom !== 'closeList' && (
              <TravelUpdateBtn formType={Number(formType)} info={info}
                               updateEnable={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['application.change.enable']}/>
            )}
            {!readOnly && <ExpireBtn formType={Number(formType)} info={info}/>}
            {!readOnly && <RestartBtn formType={Number(formType)} info={info}/>}
            {!readOnly && <BookerRefundBtn formType={Number(formType)} info={info}/>}
            {!readOnly && <BookerEndorseBtn formType={Number(formType)} info={info}/>}
            {/*{!readOnly && <GoErBtn info={info}/>}*/}
            {!readOnly && this.props.params.pageFrom === 'closeList' && (
              <CloseBtn applicationOID={this.props.params.applicationOID} apportionmentOIDs={this.state.apportionmentOIDs} budgetOIDs={this.state.budgetOIDs}/>
            )}
            {!readOnly && this.props.params.pageFrom !== 'closeList' && (
              <TransferBtn backUrlKey={backUrlKey} formType={Number(formType)} info={info} transferEnable={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['application.property.deliver.others']}/>
            )}
            {!readOnly && !payProcess &&
              (from !== 'expense' && from !== 'request') &&  //从报销单／申请单进来的关联申请单，因为是新开tab，不需要返回按钮
              <GoBackBtn backUrlKey={backUrlKey} backType={this.props.params.backType}/>}

            {confirmPay && <SurePayBtn applicantInfo={info} backType={this.props.params.backType} onlyBack={!payProcess}/>}
            {loanRefund && <LoanAndRefundBack tab={this.props.location.query.tab} info={info}/>}
            {approve && !adminApprove && !readOnlyFromUrl && <ApproveRequestBtn formType={Number(formType)} info={info} approving={!!approving && showApproveBottom} formInfo={formInfo} backUrlKey={getQueryUrlParam('backUrlKey')}/>}
            {adminApprove && !readOnlyFromUrl && <ApproveRequestBtn
              formType={Number(formType)}
              info={info} //管理员审批
              backUrlKey={getQueryUrlParam('backUrlKey')} //是否从快速查看页里跳转过来 修改人：陈行健
              approving={!!approving} formInfo={formInfo}/>}
            {rescheduleRefund && <RescheduleRefundBtn approving={!!approving} bookTaskOID={this.props.params.bookTaskOID}/>}
            {price && <PriceReviewBtn approving={!!approving} applicationOID={this.props.params.applicationOID}/>}
            {
              ['SQ0211001', 'SQ0221001', 'SQ0231001', 'SQ0021001', 'SQ0031001', 'SQ0041001'].includes(`${formCode}${info.status}`) && (
                // <div style={{position: 'absolute', left: '100px', top: 0}}>
                  <Button type="primary" onClick={this.onSubmit} loading={submitLoading}>提交</Button>
                // </div>
              )
            }
          </Affix>
        )}
        {
          ['SQ002', 'SQ003', 'SQ004'].includes(formCode) && nodeName === '预约领取' && (
            <Affix offsetBottom={0} className='bottom-bar'>
              <GoBackBtn backUrlKey={backUrlKey}/>
              <AppointmentBtn backUrlKey={backUrlKey} giftData={[...giftA, ...giftB, ...giftC]} receiverData={[...receiver]} info={info} />
            </Affix>
          )
        }
        {
          ['SQ021', 'SQ022', 'SQ023'].includes(formCode) && nodeName === '签收确认' && (
            <Affix offsetBottom={0} className='bottom-bar'>
              <GoBackBtn backUrlKey={backUrlKey}/>
              <ConfirmationBtn backUrlKey={backUrlKey} info={info} />
            </Affix>
          )
        }
        {
          ['SQ002'].includes(formCode) && nodeName === '确认签收/遗失' && (
            <Affix offsetBottom={0} className='bottom-bar'>
              {
                typeKq === '实体卡券' && info.status != '1001'  && (<Button disabled={signLoading || valid} onClick={this.onHandleSign} type="primary" style={{marginRight: '20px'}}>{"整单签收"}</Button>)
              }
              {
                typeKq === '实体卡券' && info.status != '1001'  && (<Button disabled={loseLoading || valid} onClick={this.onHandleLose} type="primary" style={{marginRight: '20px'}}>{"整单遗失"}</Button>)
              }
              {
                typeKq === '实体卡券' && info.status != '1001'  && (<Button disabled={confLoading || validConf} onClick={this.onHandleConfirm} type="primary" style={{marginRight: '20px'}}>{"整单确认"}</Button>)
              }
              <GoBackBtn backUrlKey={backUrlKey}/>
            </Affix>
          )
        }
        {
          ['SQ004'].includes(formCode) && nodeName === '确认签收/遗失' && (
            <Affix offsetBottom={0} className='bottom-bar'>
              {
                info.status != '1001'  && (<Button disabled={signLoading || valid} onClick={this.onHandleSign} type="primary" style={{marginRight: '20px'}}>{"整单签收"}</Button>)
              }
              {
                info.status != '1001'  && (<Button disabled={loseLoading || valid} onClick={this.onHandleLose} type="primary" style={{marginRight: '20px'}}>{"整单遗失"}</Button>)
              }
              {
                info.status != '1001'  && (<Button disabled={confLoading || validConf} onClick={this.onHandleConfirm} type="primary" style={{marginRight: '20px'}}>{"整单确认"}</Button>)
              }
              <GoBackBtn backUrlKey={backUrlKey}/>
            </Affix>
          )
        }
        {(readOnly && !costApplication && !approve &&!adminApprove && !rescheduleRefund && !price && !loanRefund && !payProcess && !confirmPay && !view && !audit) && (
          <Affix offsetBottom={0} className='bottom-bar'>
            <GoBackBtn backUrlKey={backUrlKey}/>
          </Affix>
        )}
        {/*{readOnly && costApplication &&*/}
        {/*( <Affix offsetBottom={0} className='bottom-bar'>*/}
        {/*  <PrintBtn info={info} printFlag={costApplication}/>*/}
        {/*</Affix>)*/}
        {/*}*/}
        <Modal title={messages('request.key527')/*信用查看*/}
               width={900}
               footer={<div><Button type={'primary'} onClick={() => this.setState({honestModalShow:false})}>{messages('request.key102')/*关闭*/}</Button></div>}
               onCancel={() => this.setState({honestModalShow:false})}
               className={'honest-view-modal'}
               visible={this.state.honestModalShow}>
          <HonestView applicant={info.applicant} jobId={info.jobId}/>
        </Modal>
      </div>
    )
  }
}

/**
 * this.props.location.query
 * {
 *    approving: 审批中（申请单审批、退改签审批）
 *    isPreVersion: 判断是否为差旅申请单最新版的上一版
 *    latestApplicationOID: 最新版本的差旅申请单OID
 *    from: 来自于哪个页面 （expense 报销单 request 申请单）
 * }
 */

BaseRequestDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    myAvailReqForms: state.cache.myAvailReqForms,
    tenant: state.login.tenant,
  }
}

const wrappedBaseRequestDetail = Form.create()(BaseRequestDetail);

export default connect(mapStateToProps)(wrappedBaseRequestDetail)
